from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate


class LoginView(APIView):
    permission_classes = [AllowAny]  # 允许未认证用户访问

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        # 验证用户
        user = authenticate(username=username, password=password)
        if not user:
            return Response(
                {'error': 'Invalid credentials'},
                status=status.HTTP_401_UNAUTHORIZED
            )

        # 生成JWT令牌
        refresh = RefreshToken.for_user(user)

        return Response({
            'refresh': str(refresh),
            'access': str(refresh.access_token),
            'user': {
                'id': user.id,
                'username': user.username,
                'email': user.email
            }
        })


# 测试用的受保护视图
class ProtectedView(APIView):
    permission_classes = [IsAuthenticated]  # 仅允许认证用户访问

    def get(self, request):
        return Response({
            'message': 'This is a protected view',
            'user': request.user.username
        })